package com.ctrip.ec.api.admin.controller.goods;
import com.ctrip.ec.api.admin.common.RequestContext;
import com.ctrip.ec.api.admin.common.ValidateException;
import com.ctrip.ec.api.admin.model.query.QueryModel;
import com.ctrip.ec.biz.dao.goods.GoodsCategoryDao;
import com.ctrip.ec.biz.entity.goods.GoodsCategoryEntity;
import com.ctrip.ec.dal.PagerSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
@RestController
@RequestMapping("/goodsCategory")
public class GoodsCategoryController{

    @Autowired
    private GoodsCategoryDao goodsCategory;

    @GetMapping("list")
    public List<GoodsCategoryEntity> list() throws SQLException {
        List<GoodsCategoryEntity> list = goodsCategory.list();
        return list;
    }
    @GetMapping("detail/{id}")
    public  GoodsCategoryEntity detail(@PathVariable Long id) throws SQLException {

        return goodsCategory.entity(id);
    }
    @PostMapping("list")
    public List<GoodsCategoryEntity> list(@RequestBody QueryModel model) throws  SQLException{
        PagerSetting setting = model.build();
        List<GoodsCategoryEntity> list = goodsCategory.list(setting);
        RequestContext.setResponseHeaderCount(setting.getRecordCount());
        return list;
    }
    @PostMapping("save")
    public  Long save(@RequestBody GoodsCategoryEntity entity) throws SQLException {
        if (entity.add()) {
            if(entity.getParentId() == 0){
                entity.setLayer(0);
                entity.setPath(",");

            }
            else {
                GoodsCategoryEntity parent = goodsCategory.entity(entity.getParentId());
                entity.setLayer(parent.getLayer() + 1);
                entity.setPath(parent.getPath() + parent.getId() + ",");
            }
        }

        //重名的判断
        if(goodsCategory.existName(entity.getName(),entity.getParentId(),entity.getId())){
            throw new ValidateException("分类不能重名");
        }

        goodsCategory.save(entity);
        return entity.getId();
    }
    @PostMapping("delete")
    public  void delete(@RequestBody List<Long> ids) throws SQLException {

        if(goodsCategory.hasGoods(ids)){
            throw new ValidateException("分类下有商品不能删除");
        }
        //需要把子分类全部删除

        goodsCategory.delete(ids);
        for(Long id : ids){
            goodsCategory.delete(id);
        }

    }
    @PostMapping("erase")
    public void erase(@RequestBody List<Long> ids) throws  SQLException{
        goodsCategory.erase(ids);
    }

    @PostMapping("unerase")
    public  void unerase(@RequestBody List<Long> ids) throws  SQLException{
        goodsCategory.unerase(ids);
    }
}
